<?php

namespace App\Common\Helpers;

use App\Common\Constants\PayWayConstants;
use App\Common\Interfaces\PaymentInterface;
use Hyperf\Di\Annotation\Inject;

class CommonNotify
{
    #[Inject]
    protected PaymentInterface $paymentService;

    public function notify($param, callable $businessCallback)
    {
        logger()->info('支付回调参数：', $param);
        $payWay = $param['pay_way'] ?? PayWayConstants::WECHAT;
        unset($param['pay_way']);
        if ($payWay == PayWayConstants::ALIPAY) {
            $alipay = $this->paymentService->alipay();
            $result = $alipay->callback($param);
            if($result['trade_status'] == 'TRADE_SUCCESS'){
                $ext = [];
                $result = call_user_func_array($businessCallback, [$param['out_trade_no'], $param['trade_no'], $ext]);
                if($result){
                    return $alipay->success();
                }
            }
        } else {
            $wechat = $this->paymentService->wechat();
            $result = $wechat->callback($param);

            $cipherText = $result['resource']['ciphertext'];
            if ($result['event_type'] == 'TRANSACTION.SUCCESS' && $cipherText['trade_state'] == 'SUCCESS') {
                $ext = [];
                $result = call_user_func_array($businessCallback, [$cipherText['out_trade_no'], $cipherText['transaction_id'], $ext]);
                if($result){
                    return $wechat->success();
                }
            }
        }
    }
}